package com.example.basic;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ProductListFragment extends ListFragment {
  /*
   * Internal class for the customized list item view
   */
  private class ProductAdapter extends ArrayAdapter<Product> {
    public ProductAdapter(ArrayList<Product> products) {
      super(getActivity(), 0, products);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      /*
       * If we weren't given a view, inflate one
       */
      if (convertView == null) {
        convertView = getActivity().getLayoutInflater()
            .inflate(R.layout.list_item_product, null);
      }
      /*
       * Configure the view for this Crime
       */
      Product p = getItem(position);
      TextView titleTextView =
          (TextView)convertView.findViewById(R.id.list_item_product_name);
      titleTextView.setText(p.getName());
      TextView idTextView =
          (TextView)convertView.findViewById(R.id.list_item_product_id);
      idTextView.setText(Integer.toString(p.getId()));
      TextView descriptionTextView =
          (TextView)convertView.findViewById(R.id.list_item_product_description);
      descriptionTextView.setText(p.getDescription());
      return convertView;
    }
  }

  private ArrayList<Product> mProducts;

  private static final String TAG = "MainFragment";

  public ProductListFragment() {
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mProducts = Inventory.getInstance(getActivity()).getProducts();

    ProductAdapter adapter = new ProductAdapter(mProducts);
    setListAdapter(adapter);
  }

  @Override
  public void onListItemClick(ListView l, View v, int position, long id) {
    Product product = (Product)(getListAdapter().getItem(position));

    // Intent i = new Intent(getActivity(), ProductActivity.class);
    Intent i = new Intent(getActivity(), ProductPagerActivity.class);
    i.putExtra(ProductPagerActivity.EXTRA_PRODUCT_ID, product.getId());
    startActivity(i);
  }
}
